//
//  SelectPhotoCollectionViewCell.m
//  Rail
//
//  Created by hychen on 2018/3/4.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "SelectPhotoCollectionViewCell.h"
#import "SelectPhotoPictureViewController.h"
#import "SelectPhotoTool.h"

@interface SelectPhotoCollectionViewCell () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/***  相机选择图片*/
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) NSMutableArray *selectImageArray;
/***  背景图片按钮*/
@property (nonatomic, weak) UIButton *backButton;
/***  打钩按钮*/
@property (nonatomic, weak) UIButton *deleteButton;
@end
@implementation SelectPhotoCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _MaxPhotoesCount = 2;
        [self setupSubviews];
    }
    return self;
}

// 子控件
- (void)setupSubviews
{
    [self setupBackButton];
    
    [self setupDeleteButton];
}

- (void)setupBackButton
{
    __weak typeof (self) weakSelf = self;
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.layer.cornerRadius = 5;
    backButton.layer.masksToBounds = YES;
    backButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [backButton addTarget:self action:@selector(backButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:backButton];
    self.backButton = backButton;
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(weakSelf.contentView);
        make.right.equalTo(weakSelf.contentView).offset(-5);
        make.top.equalTo(weakSelf.contentView).offset(5);
    }];
}

- (void)setupDeleteButton
{
    __weak typeof (self) weakSelf = self;
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"select_user_delete"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:deleteButton];
    self.deleteButton = deleteButton;
    [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(SCREEN_WIDTH/375*16);
        make.right.top.equalTo(weakSelf.contentView);
    }];
}


- (void)setModel:(SelectPhotoModel *)model
{
    _model = model;
    if (model) {
        
        // 本地缩略图
        [self.backButton setBackgroundImage:model.image forState:UIControlStateNormal];

        self.backButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
        // 如果是选择图标，那么要隐藏删除按钮，设置圆角，没设置圆角时会图标会显示不全
        if (model.isSelectPhoto) {
            self.deleteButton.hidden = YES;
            self.backButton.layer.cornerRadius = 0;
            self.backButton.layer.masksToBounds = NO;
        } else {
            self.deleteButton.hidden = NO;
            self.backButton.layer.cornerRadius = 5;
            self.backButton.layer.masksToBounds = YES;
        }
    }
}

// 删除
- (void)deleteButtonDidClicked:(UIButton *)button
{
    __weak typeof (self) weakSelf = self;
    if (self.deletePhotoBlock) {
        self.deletePhotoBlock(weakSelf.model);
    }
}

// 选择图片
- (void)backButtonDidClicked:(UIButton *)button
{
    __weak typeof (self) weakSelf = self;
    if (self.seletedPhotoBlock) {
        self.seletedPhotoBlock(weakSelf.model);
    }
    
}

// 弹出图片选择器
- (void)showPhotoSelectorVc
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied) {
        //相册权限未开启
        [self showAlertViewToController];
        return;
    }
    __weak typeof (self) weakSelf = self;
    SelectPhotoPictureViewController *vc = [[SelectPhotoPictureViewController alloc] init];
    vc.maxSelectImageCount = self.MaxPhotoesCount - self.selectImageArray.count;
    vc.selectPhotoFinishBlock = ^(NSMutableArray *assetArray) {
        // 选中照片
        [weakSelf handelSelectPhotoArray:assetArray];
    };
    
    vc.takePictureCameraBlock = ^(){
        // 打开照相机
        [weakSelf openCameraPicker];
    };
    
    BaseNavigationController *navVc = [[BaseNavigationController alloc] initWithRootViewController:vc];
    [[BaseNavigationController rootNavigationController] presentViewController:navVc animated:YES completion:nil];
}

// 处理选中图片
- (void)handelSelectPhotoArray:(NSMutableArray *)photoArray
{
    NSMutableArray *imageModelArray = [SelectPhotoTool getPostImageModelArrayWithAssetsArray:photoArray];
    [self.selectImageArray addObjectsFromArray:imageModelArray];
}

// 打开相机
- (void)openCameraPicker
{
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                       message:@"你的设备没有相机!"
                                                      delegate:self
                                             cancelButtonTitle:nil
                                             otherButtonTitles:@"我知道了",
                              nil];
        [alert show];
    } else {
        if ([BMPhotoIOAuthTool checkCameraAuth]) {
            [[BaseNavigationController rootNavigationController] presentViewController:self.imagePicker animated:YES completion:nil];
        }
    }
}

- (void)showAlertViewToController
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    
    UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提醒" message:[NSString stringWithFormat:@"请在iPhone的“设置->隐私->照片”开启%@访问你的手机相册",app_Name] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alerView show];
}

// 调整选择照片尺寸
- (void)resizeButtonWithSmall:(BOOL)isSmall
{
    __weak typeof (self) weakSelf = self;
    if (isSmall) {
        [self.backButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.contentView).offset(25);
            make.top.equalTo(weakSelf.contentView).offset(35);
        }];
    } else {
        [self.backButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.contentView).offset(-5);
            make.top.equalTo(weakSelf.contentView).offset(5);
        }];
    }
    [self.contentView layoutIfNeeded];
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [_imagePicker setAllowsEditing:NO];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}
@end
